package com.sso.oa.controller;

import com.sso.common.dto.ApiResponse;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * OA 系统主控制器
 * 
 * @author SSO System
 * @since 2024-01-01
 */
@Controller
public class OaController {

    /**
     * 首页（登录后）
     */
    @GetMapping("/")
    public String home(@AuthenticationPrincipal OidcUser principal, Model model) {
        if (principal != null) {
            model.addAttribute("username", principal.getPreferredUsername());
            model.addAttribute("fullName", principal.getFullName());
            model.addAttribute("email", principal.getEmail());
            return "home";
        }
        return "index"; // 未登录用户显示欢迎页面
    }

    /**
     * 欢迎页面（登录前）
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "index";
    }

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * 仪表板
     */
    @GetMapping("/dashboard")
    public String dashboard(@AuthenticationPrincipal OidcUser principal, Model model) {
        if (principal != null) {
            model.addAttribute("username", principal.getPreferredUsername());
            model.addAttribute("fullName", principal.getFullName());
            model.addAttribute("email", principal.getEmail());
            model.addAttribute("authorities", principal.getAuthorities());
        }
        return "dashboard";
    }

    /**
     * 文档管理页面
     */
    @GetMapping("/documents")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('oa:read')")
    public String documents(@AuthenticationPrincipal OidcUser principal, Model model) {
        model.addAttribute("username", principal.getPreferredUsername());
        return "documents";
    }

    /**
     * 流程管理页面
     */
    @GetMapping("/workflows")
    @PreAuthorize("hasAuthority('SCOPE_write') or hasAuthority('oa:write')")
    public String workflows(@AuthenticationPrincipal OidcUser principal, Model model) {
        model.addAttribute("username", principal.getPreferredUsername());
        return "workflows";
    }

    /**
     * 系统管理页面
     */
    @GetMapping("/admin")
    @PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('oa:all')")
    public String admin(@AuthenticationPrincipal OidcUser principal, Model model) {
        model.addAttribute("username", principal.getPreferredUsername());
        return "admin";
    }

    /**
     * API: 获取文档列表
     */
    @GetMapping("/api/documents")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('oa:read')")
    @Cacheable(value = "documents", key = "#principal.preferredUsername")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getDocuments(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> data = new HashMap<>();
        data.put("documents", java.util.List.of(
                Map.of("id", 1, "title", "年度工作计划", "author", "张三", "createTime", LocalDateTime.now().minusDays(5)),
                Map.of("id", 2, "title", "项目需求文档", "author", "李四", "createTime", LocalDateTime.now().minusDays(3)),
                Map.of("id", 3, "title", "会议纪要", "author", "王五", "createTime", LocalDateTime.now().minusDays(1))
        ));
        data.put("total", 3);
        data.put("currentUser", principal.getPreferredUsername());
        
        return ApiResponse.success("获取文档列表成功", data);
    }

    /**
     * API: 获取待办事项
     */
    @GetMapping("/api/todos")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('oa:read')")
    @Cacheable(value = "todos", key = "#principal.preferredUsername")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getTodos(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> data = new HashMap<>();
        data.put("todos", java.util.List.of(
                Map.of("id", 1, "title", "审批请假申请", "priority", "高", "dueDate", LocalDateTime.now().plusDays(1)),
                Map.of("id", 2, "title", "完成月度报告", "priority", "中", "dueDate", LocalDateTime.now().plusDays(3)),
                Map.of("id", 3, "title", "参加团队会议", "priority", "低", "dueDate", LocalDateTime.now().plusHours(2))
        ));
        data.put("total", 3);
        data.put("currentUser", principal.getPreferredUsername());
        
        return ApiResponse.success("获取待办事项成功", data);
    }

    /**
     * API: 创建文档
     */
    @GetMapping("/api/documents/create")
    @PreAuthorize("hasAuthority('SCOPE_write') or hasAuthority('oa:write')")
    @ResponseBody
    public ApiResponse<String> createDocument(@AuthenticationPrincipal OidcUser principal) {
        // 模拟创建文档
        return ApiResponse.success("文档创建成功，文档ID: DOC-" + System.currentTimeMillis());
    }

    /**
     * API: 用户信息
     */
    @GetMapping("/api/user/info")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getUserInfo(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", principal.getPreferredUsername());
        userInfo.put("fullName", principal.getFullName());
        userInfo.put("email", principal.getEmail());
        userInfo.put("authorities", principal.getAuthorities());
        userInfo.put("claims", principal.getClaims());
        
        return ApiResponse.success("获取用户信息成功", userInfo);
    }
} 